/**
 *
 */
package co.fitstart.api.web.controller.content;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;

import co.fitstart.api.service.ContentService;
import co.fitstart.entity.content.Article;
import co.fitstart.entity.content.Module;

/**
 * @author downpour
 *
 */
@Controller
@RequestMapping("/v1")
public class ArticleApiController {

    @Autowired
    private ContentService contentService;

    /**
     * List all articles
     *
     * @param keyword
     * @param moduleId
     * @param page
     * @return
     */
    @RequestMapping(value = "/articles", method = RequestMethod.GET)
    public @ResponseBody String list(@RequestParam(value = "q", required = false) String keyword,
                                     @RequestParam(value = "m", required = false) Long moduleId,
                                     Page page) {

        Result result = new Result();

        List<Article> articles = contentService.listArticle(moduleId, keyword, page);
        
        result.success()
              .data("page", page)
              .data("articles", articles);

        if(StringUtils.isNotEmpty(keyword)) {
            result.data("q", keyword);
        }
        if(moduleId != null) {
            Module module = contentService.getModule(moduleId);
            result.data("m", moduleId)
                  .data("moduleName", module == null ? "" : module.getName());
        }

        return JsonUtils.toJsonString(result);
    }
    
    /**
     * List all articles
     *
     * @param keyword
     * @param moduleId
     * @param page
     * @return
     */
    @RequestMapping(value = "/new-articles", method = RequestMethod.GET)
    public @ResponseBody String listNew() {

        Result result = new Result();

        List<Article> articles = contentService.listNewArticle();
        
        result.success()
              .data("newArticles", articles);

        return JsonUtils.toJsonString(result);
    }

    /**
     *
     * @return
     */
    @RequestMapping(value = "/modules", method = RequestMethod.GET)
    public @ResponseBody String modules() {
        Result result = new Result();
        List<Module> modules = contentService.listModules();
        result.success().data("modules", modules);
        return JsonUtils.toJsonString(result);
    }

}
